#include <stdio.h>
#include <linux/unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <pthread.h>
#include "test_barrier_header.h"


void *thread_function( void *ptr );
void *destroy_function( void *ptr );

int main(int argc, char *argv[])
{
	
	int j;

	/*if(argc!=3)
	{
		printf(" You need to pass two args N(barrier size) and M(processes)");
		return -1;
	}*/

	int N=5
	int M=4;

	int id =(int)barriercreate(N);
	
	
	if(id < 0)
	{
		perror("barriercreate: ");
		printf("Barrier Create error \n");
		return -1;
	}
	else{
		printf("Barrier Created\n");
	}
	

	pthread_t threads[M];
	
	for(j=0;j<M;j++)
	{
		if(j==3)
		{
			pthread_create( &threads[j], NULL, destroy_function, (void*) &id);
		}
		else{
		pthread_create( &threads[j], NULL, thread_function, (void*) &id);
		}
	}

	for(j=0;j<M;j++)
	{
	pthread_join( threads[j], NULL);
	
	}


	

	
	return 0;
}


void *thread_function( void *ptr )
{
     
	 int *idptr = (int *) ptr;
	 
	 printf("Thread number %ld\n", pthread_self());
	 printf("Before Wait\n");
	 int ret=barrierwait(*idptr);
	 if(ret!=0)
	 {
		 printf("Error in Wait\n");

	 }
	 printf("Wait Over- Now Returning to main %ld\n", pthread_self());
	 return;
     
}

void *destroy_function( void *ptr )
{
     
	 int *idptr = (int *) ptr;
	 
	 printf("Thread number %ld\n", pthread_self());
	 
	 int ret=barrierdestroy(*idptr);
	 if(ret<0)
	 {
		 printf("Error in Calling Destroy in Between\n");

	 }else{
	
		 printf("Woke up :%d  \n", ret);

	 	 }
	 
	 return;
     
}

